import React, { Component } from 'react'
import {Button,Card,Row, Col, Divider} from 'antd'
import PubSub from 'pubsub-js'
import flvjs from 'flv.js'
import {createWebSocket,closeWebSocket,websocket} from '../../utils/websocket'
// 引入api
import {detectCurFrame} from '../../api/video'
// 引入工具类
import {createFormData} from '../../utils/creatFormData'
import './index.scss'
// let boxpool = [[0.5966184139251709, 0.49981042742729187, 0.6493131518363953, 0.6164175868034363], [0.2250565141439438, 0.8328591585159302, 0.26245325803756714, 0.9108520150184631]];
// let namedboxpool = ['ysx','zlf'];
let boxpool = [];
let namedboxpool = [];
let imageUrl = "";
const style = { background: '#fff', padding: '0px 14px' };
export default class Video extends Component {
    state = {
        box:[],
        id:[],
        stream_name : '',
        user_id : '',
        user_name : '',
        SERVER : '127.0.0.1:8080',
        TOKEN : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIyIiwiZXhwIjoxNjIwMjgyMzg5LCJzY29wZXMiOlsiYXBwdXNlciJdfQ.zYNlrUdrbQv6QCnSwTfrTYhf_HJlr5hUW7Xht96kyH0"   
    }

    draw = (ctx,boxes,id,width,height) => { 
        // console.log(boxes,id)
        let i = 0      
        while(boxes.length > 0 && i<boxes.length){
            // var box = new Array(boxes[i])
            let box = new Array(boxes[i])
            // console.log(box)
            var na = id[i]
            let aa = new Array(box);
            let a = aa[0][0]
            // console.log('x,y,w,h',a[0],a[1],a[2],a[3])
            // console.log(i)
            // console.log('a',a)
            ctx.fillStyle = "rgba(255, 0, 0, 0.3)";
            ctx.fillRect(a[0]*width, a[1]*height, a[2]*width-a[0]*width, a[3]*height-a[1]*height);
            ctx.font="25px Arial";
            ctx.strokeRect(a[0]*width, a[1]*height, a[2]*width-a[0]*width, a[3]*height-a[1]*height);
            ctx.fillText(na, a[0]*width, a[1]*height-7);
            i+=1
        }       
    }

    start = ($video) => {
        const {stream_name} = this.props
        if($video){
            if (flvjs.isSupported()) {
                // console.log("sdgfj")
                let flvPlayer = flvjs.createPlayer({
                                    type: 'flv',
                                    isLive: true,
                                    cors: true,
                                    url: `http://www.dpl402.site:2180/live?port=1935&app=live&stream=${stream_name}`,
                                    // url: `http://119.45.160.230/live?port=1935&app=live&stream=${stream_name}`,
                                    // url:'http://120.27.241.217/livestreamk-1616722889.flv',
                                    // url: `http://58.200.131.2/livetv?port=1935&app=livetv&stream=cctv1`,
                                    // url: 'http://120.27.241.21/rtmp/records/livestream-1615514859.flv',
                                    duration: 0,
                                }, {
                                    enableStashBuffer: false,
                                    isLive: true,
                                    lazyLoad: false,
                                    lazyLoadMaxDuration: 0,
                                    lazyLoadRecoverDuration: 0,
                                    deferLoadAfterSourceOpen: false,
                                    fixAudioTimestampGap: false,
                                }
                            );
                            flvPlayer.attachMediaElement($video);
                            flvPlayer.load(); //加载
                            flvPlayer.play();
                            this.flvPlayer = flvPlayer;
                            //避免时间长时间积累缓冲导致延迟越来越高
                            // setInterval(() => {
                            //     if (!flvPlayer.buffered.length) {
                            //         return;
                            //     }
                            //     let end = flvPlayer.buffered.end(0);
                            //     let diff = end - flvPlayer.currentTime;
                            //     if (diff >= 1.5) {
                            //         flvPlayer.currentTime = end - 0.1;
                            //     }
                            // }, 3 * 10 * 1000);               
            }
        }
        
    }
    
    toCanvas = ()=>{
        var canvas = document.getElementById('c1');
        if(canvas){
            var context = canvas.getContext("2d");
        } 
        // console.log(boxpool,namedboxpool)       
        const {$video} = this.refs
        context.drawImage($video, 0, 0, canvas.width, canvas.height);//绘制视频
        this.draw(context,boxpool,namedboxpool,canvas.width,canvas.height)
        this.aFrameId=window.requestAnimationFrame(this.toCanvas)
    }
    
    dataURLtoFile = (dataurl,filename) => { 
        // console.log('图片地址为：',dataurl)
        // console.log('图片名称',filename)
	    var arr = dataurl.split(','),
	        mime = arr[0].match(/:(.*?);/)[1],
	        bstr = atob(arr[1]),
	        n = bstr.length,
	        u8arr = new Uint8Array(n);
	    while (n--) {
	        u8arr[n] = bstr.charCodeAt(n);
	    }
	    return new File([u8arr], filename, { type: mime });
    }

    cut = ()=>{   
        var canvas = document.getElementById('c1');
        var context = canvas.getContext("2d");
        imageUrl=context.canvas.toDataURL();
        // console.log(imageUrl)
        var na = 'sfsdf'
                var file = this.dataURLtoFile(imageUrl,na)
                console.log('截取的图片文件为:',file)
                let sailorData={}
                sailorData.file=file
                if(file){
                    detectCurFrame(createFormData(sailorData)).then(response => {
                        console.log(response.data)           
                        if(JSON.stringify(response.data) === "{}"){
                            namedboxpool = []
                            boxpool = []
                        }else{
                            const {id,box} = response.data
                            // this.id = id
                            // this.box = box
                            console.log('从后台得到的人脸数据',id,box)
                            namedboxpool = id
                            boxpool = box
                            // this.toCanvas()
                        }
                    }).catch(error => {
                        console.log(error)
                        // alert("上传图片失败")
                    })
                }
                else{
                    // alert("您还未上传图片");
                }
    }

    componentDidMount () {
        this.token = PubSub.subscribe('str_list',(_,data)=>{
            this.setState(data)            
        })
        boxpool = [];
        namedboxpool = [];
        // let url=`ws://127.0.0.1:8080/ws?rtmp=${this.props.stream_name}&token=${this.state.TOKEN}`;//服务端连接的url
        // let url=`ws://10.138.91.196:8080/ws?rtmp=${this.props.stream_name}&token=${this.state.TOKEN}`;//服务端连接的url
        // let url=`ws://127.0.0.1:8080/ws?rtmp=cctv1&token=${this.state.TOKEN}`
        // this.websocket = createWebSocket(url)
        // this.websocket.onmessage =  (event)=>{          
        //     console.log("video中的data",event.data)
        //     if(event.data==='null'||event.data === `{"msg": "ready"}`||event.data==='[]'){  
        //         console.log('if里的id',this.state.id)             
        //     }else{   
        //         console.log('event.data为：', event.data)            
        //         const {id,box}=JSON.parse(event.data)
        //         // this.id = id
        //         // this.box = box
        //         console.log('从后台得到的人脸数据',id,box)
        //         namedboxpool = id
        //         boxpool = box
        //         this.setState({
        //             box:box,
        //             id:id,
        //         })               
        //     }                                
        // }
        var canvas = document.getElementById('c1');
        var context = canvas.getContext("2d");
        if(canvas){
            const {$video} = this.refs
            this.start($video) 
            this.toCanvas()                      
        }       
    }

    componentWillUnmount () {
        if (this.flvPlayer) {
            this.flvPlayer.unload();
            this.flvPlayer.detachMediaElement();
        }
        let boxpool = [];
        let namedboxpool = [];
        window.cancelAnimationFrame(this.aFrameId)
        this.aFrameId = null
        // this.websocket.close()
    }

    togglelist = ()=>{
        this.props.switchForm('list')
    }

    toggledetect = (id,box)=>{    
        console.log(this.websocket)
        // console.log(box)
        this.websocket.send('{"event":"detect"}')  
        // this.drawBoxs(id,box)        
    }

    render() {
        // console.log('UI组件接收到的props是',this.props)
        // console.log(this.box,this.id)
        // const {stream_name} = this.props
        const {stream_info,stream_name} = this.props
        console.log(stream_info)
        const {user_name,user_id} = stream_info
        return (            
                <div className="mainclass">
                    <Divider orientation="left">实时检测信息</Divider>
                    <Row >
                    <Col className="gutter-row" span={4}>
                        <div style={style}><p><strong>推流名</strong>：{stream_name}</p></div>
                    </Col>
                    <Col className="gutter-row" span={4}>
                        <div style={style}><p><strong>执法人编号</strong>：{user_id}</p></div>
                    </Col>
                    <Col className="gutter-row" span={4}>
                        <div style={style}><p><strong>执法人姓名</strong>：{user_name}</p></div>
                    </Col>
                    </Row>
                    
                    <br/>
                    <div className="videos">
                        <video style={{backgroundColor:'black'}} ref="$video" name="videoElement" id="videoElement" className="centerVideo" controls muted autoPlay width="600"
                            height="300">
                            Your browser is too old which doesn't support HTML5 video.                          
                        </video>&nbsp;
                        {/* <video id="tes" controls width="270" autoplay>
                            <source src="tt.mp4" type='video/mp4'/>
                        </video> */}
                        <canvas style={{border:'1px solid #d3d3d3'}} ref={this.canvas_dispaly} id="c1" width="580" height="380"/>
                        {/* <div className="site-card-border-less-wrapper">
                            <Card title="相关信息" bordered={false} style={{ width: 300 }}>
                            
                            
                            
                            </Card>                        
                        </div> */}
                    </div>
                    <br />
                    <br />
                    <Button className="hh" onClick={this.togglelist}>返回列表</Button>&nbsp;&nbsp;
                    <Button onClick={this.cut}>点击检测</Button>
                    {/* <Button onClick={()=>{this.toggledetect(this.state.id,this.state.box)}}>检测</Button> */}
                </div>
                        
        )
    }
}



